package edu.bmstu.rslab;

import javax.swing.*;
import java.awt.geom.Point2D;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

/**
 * Created by Chikh (using IntelliJ IDEA).
* Date: 15.05.2009
* Time: 15:04:20
*/
class setPathAction extends AbstractAction {
    private final VideoPanel videoPanel;
    private final Camera camera;
    private final Guidance guidance;
    private final ArrayList<Point2D> checkPoints;
    private final CoordinateSystemPanel coordinateSystemPanel;
    private final Action startAction;
    private final Action stopAction;
    private final Translator translator;
    private final Detector directionDetector;

    public setPathAction(VideoPanel videoPanel, Camera camera, Guidance guidance, ArrayList<Point2D> checkPoints,
                         CoordinateSystemPanel coordinateSystemPanel, Action startAction, Action stopAction,
                         Translator translator, Detector directionDetector) {
        super("Set path");
        this.videoPanel = videoPanel;
        this.camera = camera;
        this.guidance = guidance;
        this.checkPoints = checkPoints;
        this.coordinateSystemPanel = coordinateSystemPanel;
        this.startAction = startAction;
        this.stopAction = stopAction;
        this.translator = translator;
        this.directionDetector = directionDetector;
        setEnabled(false);
    }

    public void actionPerformed(ActionEvent e) {
        setEnabled(false);
        videoPanel.addMouseListener(new MouseAdapter() {


            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() >= 2) {
                    videoPanel.removeMouseListener(this);
                    Point2D initialDirection = translator.translate(directionDetector.detect(camera.getImage()));
                    ArrayList<Point2D> pathPoints = guidance.calculateRoute(checkPoints, initialDirection);
                    for (Point2D point : pathPoints) {
                        coordinateSystemPanel.addPathPoint(point);
                    }
                    startAction.setEnabled(true);
                    stopAction.setEnabled(true);
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
                Point2D point = translator.translate(videoPanel.getScaledPoint(new Point2D.Double(e.getX(),
                        e.getY())));
                if (!(checkPoints.isEmpty())? (point.distance(checkPoints.get(checkPoints.size()
                        - 1)) > 0) : (true)) {
                    videoPanel.addToCheckPoints(new Point2D.Double(e.getX(), e.getY()));
                    checkPoints.add(point);
                    coordinateSystemPanel.addPathPoint(point);
                }
            }
        });
    }
}
